﻿using AutoMapper;
using Domain.Production_Modules;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.Production_Modules.PurchaseOrder;
using ReturnValue;
using Yitter.IdGenerator;

namespace MES.Server.API.Application.Handler.Production_Modules.PurchaseOrder
{
    public class AddPurchaseOrderHander : IRequestHandler<AddPurchaseOrderCommand, ApiResult<int>>
    {
        private readonly IRepository<PurchaseOrderModel> purchaseOrderRepo;
        private readonly IMapper mapper;
        public AddPurchaseOrderHander(IRepository<PurchaseOrderModel> purchaseOrderRepo, IMapper mapper)
        {
            this.purchaseOrderRepo = purchaseOrderRepo;
            this.mapper = mapper;
        }
        /// <summary>
        /// 物料采购单发布
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(AddPurchaseOrderCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();
            var Ask = purchaseOrderRepo.GetAll().Where(x => x.PurchaseOrderCode == request.PurchaseOrderCode).FirstOrDefault();
            if (Ask != null)
            {
                result.Message = "物料采购申请单号已存在,无法重复申请";
                result.Code = StatusCode.Fail;
                return await Task.FromResult(result);
            }
            var model = mapper.Map<PurchaseOrderModel>(request);
            model.IsDel = false;
            model.CreateTime = DateTime.Now;
            model.Id = YitIdHelper.NextId();
            if(model!=null)
            {
                await purchaseOrderRepo.AddAsync(model);
                result.Message = "物料采购单发布成功";
                result.Code = StatusCode.Success;
                return await Task.FromResult(result);
            }
            else
            {
                result.Message = "物料采购单发布失败";
                result.Code = StatusCode.Success;
                return await Task.FromResult(result);
            }
        }
    }
}
